package org.jeecg.modules.user.member.controller;




import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.dto.MemberDTO;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.user.member.service.RealAuthService;
import org.jeecg.modules.utils.BikeResult;
import org.jeecg.modules.utils.YueYueNiaoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;


@Validated
@RestController
@CrossOrigin
@RequestMapping("/auth")
@Api(value = "实人认证", description = "实人认证", tags = {"实人认证"})
public class RealAuthController {

    @Autowired
    private RealAuthService realAuthService;
    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation(value = "发起认证请求", notes = "发起认证请求")
    @PostMapping("/AliAuthen")
    public BikeResult aliAuthen(HttpServletRequest request) {
        String accessToken = request.getHeader("X-Access-Token");
        // 解密获得username，用于和数据库进行对比
        String phone = "AliAuthen"+JwtUtil.getUsername(accessToken);
        boolean b = redisUtil.hasKey(phone);
        if (b){
            int o = (int) redisUtil.get(phone);
            if (o>5){
                return BikeResult.ok("0","当日认证次数达到上限",null);
            }
        }
        return realAuthService.aliAuthen();
    }


    @ApiOperation(value = "查询认证结果", notes = "查询认证结果")
    @GetMapping("/getAliResult")
    public BikeResult getAliResult(@RequestParam("RequestId") String RequestId, HttpServletRequest request) {

        return realAuthService.getAliResult(RequestId,request);
    }

    @ApiOperation(value = "校验认证次数",notes = "校验认证次数")
        @GetMapping("/getCertificationCount")
    public BikeResult getCertificationCount(HttpServletRequest request){
        Date dayEnd = YueYueNiaoUtils.getToDayEnd();
        Date date = new Date();
        long toDayEnd = (dayEnd.getTime()-date.getTime())/1000;
        String accessToken = request.getHeader("X-Access-Token");
        // 解密获得username，用于和数据库进行对比
        String phone = "AliAuthen"+JwtUtil.getUsername(accessToken);
        boolean b = redisUtil.hasKey(phone);
        if (b){
            int o = (int) redisUtil.get(phone);
            if (o>5){
                return BikeResult.ok("0","当日认证次数达到上限",null);
            }
        }

        if (b){
            int o = (int) redisUtil.get(phone);
            if (o<=5){
                o++;
            }
            redisUtil.set(phone,o,toDayEnd);
        }else {
            redisUtil.set(phone,1,toDayEnd);
        }
        return BikeResult.ok("1","可继续认证",null);
    }
}
